/**
 *  Copyright 2013 Mike Reed
 *
 *  COMP 590 -- Fall 2013
 */

#include "GSlide.h"
#include "GXWindow.h"
#include "GBitmap.h"
#include "GPaint.h"
#include "GContext.h"
#include "GRect.h"
#include "GRandom.h"
#include "GTime.h"
#include "app_utils.h"
#include <string>
#include <math.h>

class SlideWindow : public GXWindow {
    const GBitmap*  fBitmaps;
    int             fBitmapCount;

    GSlide*         fSlide;
    GSlide::Iter    fIter;

    void initSlide() {
        fSlide->initWithBitmaps(fBitmaps, fBitmapCount);
    }

public:
    SlideWindow(int w, int h,
               const GBitmap bitmaps[], int bitmapCount) : GXWindow(w, h) {
        fStartTime = GTime::GetMSec();
        fCounter = 0;

        fBitmaps = bitmaps;
        fBitmapCount = bitmapCount;

        fSlide = fIter.next();
        this->initSlide();
    }

    virtual ~SlideWindow() {
        for (int i = 0; i < fBitmapCount; ++i) {
            free(fBitmaps[i].fPixels);
        }
        delete fSlide;
    }
    
protected:
    virtual void onDraw(GContext* ctx) {
        ctx->clear(GColor::Make(1, 1, 1, 1));
        
        GMSec now = GTime::GetMSec();
        fSlide->draw(ctx);

        this->requestDraw();

        if (++fCounter > 100) {
            char buffer[100];
            int dur = GTime::GetMSec() - fStartTime;
            sprintf(buffer, "FPS %8.1f", fCounter * 1000.0 / dur);
            this->setTitle(buffer);

            fStartTime = GTime::GetMSec();
            fCounter = 0;
        }
    }
    
    virtual bool onKeyPress(const XEvent& evt) {
        delete fSlide;
        fSlide = fIter.next();
        if (!fSlide) {
            fIter.reset();
            fSlide = fIter.next();
        }
        this->initSlide();
        this->requestDraw();

        return this->INHERITED::onKeyPress(evt);
    }
    
private:
    GMSec   fStartTime;
    int     fCounter;

    typedef GXWindow INHERITED;
};

int main(int argc, char const* const* argv) {
    int fileCount = argc - 1;
    int bitmapCount = 0;
    GBitmap* bitmaps = new GBitmap[fileCount];
    for (int i = 0; i < fileCount; ++i) {
        if (GReadBitmapFromFile(argv[i + 1], &bitmaps[i])) {
            bitmapCount += 1;
        }
    }

    return SlideWindow(640, 480, bitmaps, bitmapCount).run();
}

